package com.yonyou.rabbitmq.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;

@Component
@Slf4j
public class DealMsgExecutor {

    private ExecutorService executor = new ThreadPoolExecutor(2,
            40,
            0L,
            TimeUnit.SECONDS,
            //能够接收请求产生的消息队列即可，设置过大会浪费内存
            new LinkedBlockingQueue<>(800),
            new MessageThreadFactory(),
            new MessageRejectedHandler());

    public void putThread(Runnable r) {
        log.info("DealMsgExecutor->putThread: " + executor.toString());
        //业务线程
        executor.submit(r);
    }

    class MessageThreadFactory implements ThreadFactory {
        @Override
        public Thread newThread(Runnable r) {
            //实际cpu调用的线程
            Thread thread = new Thread(r);
            thread.setName("DealMsgExecutor");
            return thread;
        }
    }

    class MessageRejectedHandler implements RejectedExecutionHandler {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            log.error("Task" + r.toString() + " rejected from " + executor.toString());
        }
    }
}
